/**
 * 打尺记录
 * Created by 11057 on 2018/2/28.
 */
import { Component, ElementRef } from '@angular/core';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { ImagePicker } from "@ionic-native/image-picker";
import { IonicPage, NavController, ToastController, ActionSheetController, NavParams, AlertController, LoadingController } from 'ionic-angular';
import { RuleRecordApi } from '../../api/rule-record/RuleRecordApi';
import { ApiHost } from '../../api/Constants';

@IonicPage()
@Component({
  selector: 'page-rule-record',
  templateUrl: 'rule-record.html'
})
export class RuleRecord {
  private imgData: string = "assets/imgs/photo.jpg";
  private length: string;
  private width: string;
  private height: string;
  private weight: string;
  private description: string = "这是备注/描述...";
  private stalength: string;
  private stawidth: string;
  private staheight: string;
  private staweight: string;
  private qrcode: string;
  private parms: any;
  private materiel: any;
  private latitude: string;
  private longitude: string;
  private positionId: string;
  private picUrl: string = "";//初始化图片url,上传成功接收图片路径
  private fileTransfer: FileTransferObject = this.transfer.create();
  private photoNumber: number;
  private disTag: boolean;

  constructor(private ele: ElementRef, public navCtrl: NavController, private loadingCtrl: LoadingController, private transfer: FileTransfer, public actionSheetCtrl: ActionSheetController, private alertCtrl: AlertController, public params: NavParams, private toastCtrl: ToastController, public imagePicker: ImagePicker, private camera: Camera, private ruleRecordApi: RuleRecordApi) {
    this.qrcode = params.get("qrcode");
    this.positionId = params.get("positionId");
    this.materiel = params.get("materiel");
    this.length = this.materiel.materielLength;
    this.width = this.materiel.materielWidth;
    this.height = this.materiel.materielHeight;
    this.weight = this.materiel.materielEmptyWeight;
    this.stalength = this.length;
    this.stawidth = this.width;
    this.staheight = this.height;
    this.staweight = this.weight;
    this.photoNumber = 0;
    this.disTag = true;
  }

  check() {
    let patrn = /^[0-9]+(.[0-9]{1,3})?$/;
    if (!patrn.test(this.length)) {
      this.showMsg('长度错误! 请输入正数,且保留3位小数');
      return false;
    }
    if (!patrn.test(this.width)) {
      this.showMsg('宽度错误! 请输入正数,且保留3位小数');
      return false;
    }
    if (!patrn.test(this.height)) {
      this.showMsg('高度错误! 请输入正数,且保留3位小数');
      return false;
    }
    if (!patrn.test(this.weight)) {
      this.showMsg('重量错误! 请输入正数,且保留3位小数');
      return false;
    }
    return true;
  }

  /**
   * 打开摄像头拍照
   */
  takePhoto() {
    const options: CameraOptions = {
      quality: 50,                                                   //相片质量 0 -100
      destinationType: this.camera.DestinationType.DATA_URL,        //DATA_URL 是 base64   FILE_URL 是文件路径
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum: true,                                       //是否保存到相册
      // sourceType: this.camera.PictureSourceType.CAMERA ,         //是打开相机拍照还是打开相册选择  PHOTOLIBRARY : 相册选择, CAMERA : 拍照,
    }
    this.camera.getPicture(options).then((imageData) => {
      let base64Image = 'data:image/jpeg;base64,' + imageData;
      this.imgData = base64Image;
      this.disTag = false;
    }, (err) => {
      //this.showMsg("相机异常")
    });
  }

  /**
   * 图片上传
   */
  upload() {
    const apiPath = ApiHost + "/api/ruleRecord/savePhoto?token=" + localStorage.getItem("token");//接口地址
    let options: FileUploadOptions = {
      fileKey: 'file',
      fileName: 'name.jpg',   //文件名称
      headers: {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'//不加入 发生错误！！
      },
      // 如果要传参数，写这里
      params: {
        maxSize: 5000000,
        modularName: 'CNL',
        allowType: 'jpg',
      }
    };
    let loader = this.loadingCtrl.create({
      content: "正在上传...",
    });
    loader.present();
    this.cutImageBase64(this.imgData, "600", "600", (newImgData) => {
      this.fileTransfer.upload(newImgData, apiPath, options).then((data) => {
        if (data.responseCode == 200) {
          this.photoNumber = this.photoNumber + 1;
          let result = JSON.parse(data.response);
          if (result.state) {
            this.disTag = true;
            loader.dismiss();
            this.showMsg(result.msg);
            this.picUrl = this.picUrl + result.url + "#";//上传成功的图片路径返回
          } else {
            loader.dismiss();
            this.showMsg(result.msg);
          }
        } else {
          loader.dismiss();
          this.showMsg("系统异常");
        }
      }, (err) => {
        this.disTag = true;
        loader.dismiss();
        this.showMsg("服务器错误,请重新拍照上传");
      });
    });

  }

  /**
   * 保存
   */
  saveRecord() {
    if (this.check()) {
      var options = {
        enableHighAccuracy: true,  // 是否使用 GPS
        maximumAge: 60000,         // 缓存时间
        timeout: 27000,            // 超时时间
        coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
      }
      navigator.geolocation.getCurrentPosition((position: any) => {
        //获取经纬度
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        //设置参数
        this.parms = {
          "qrcode": this.qrcode,
          "latitude": this.latitude,
          "longitude": this.longitude,
          "positionId": this.positionId,
          "resourceId": this.materiel.materielId,
          "resourceCode": this.materiel.materielCode,
          "resourceName": this.materiel.materielName,
          "length": this.length,
          "width": this.width,
          "height": this.height,
          "weight": this.weight,
          "description": this.description,
          "picUrl": this.picUrl//如果不拍照,默认传空字符串
        };
        //调接口
        this.saveRuleRecord(this.parms);
      }, (error: any) => {
        this.showMsg(error);
      }, options);
    }
  }

  saveRuleRecord(param: object) {
    if ("assets/imgs/photo.jpg" != this.imgData && this.picUrl == "") {
      this.showMsg("请先上传图片");
      return;
    }
    let loader = this.loadingCtrl.create({
      content: "正在提交...",
    });
    loader.present();
    const http$ = this.ruleRecordApi.ruleRecord(param);
    http$.subscribe((val: any) => {
      let saveResult = JSON.parse(val);
      if (saveResult.state) {
        loader.dismiss();
        let alert = this.alertCtrl.create({
          title: saveResult.msg,
          message: '点击确定继续查验货物',
          buttons: [{
            text: '确定',
            handler: data => {
              //点击确定,跳转到货物检测扫描界面
              this.navCtrl.push("RuleScan", { "positionId": this.positionId });
            }
          }]
        });
        alert.present();
      } else {
        loader.dismiss();
        this.showMsg(saveResult.msg);
      }
    });

    /*const http$ = this.ruleRecordApi.ruleRecord(param);
    http$.subscribe((val: any) => {
      let saveResult = JSON.parse(val);
      if (saveResult.state) {
        let alert = this.alertCtrl.create({
          title: '消息',
          subTitle: saveResult.msg,
          buttons: ['OK']
        });
        alert.present();

      } else {
        this.showMsg(saveResult.msg);
      }
    });*/
  }


  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }

  cutImageBase64(base64: string, width: string, height: string, callback) {
    let newbase64: string;
    if (base64 == "assets/imgs/photo.jpg" || base64 == "") {
      newbase64 = "assets/imgs/photo.jpg";
      callback ? callback(newbase64) : null; //调用回调函数
    } else {
      let _img = new Image();
      _img.src = base64;
      _img.onload = function () {
        let _canvas = document.createElement("canvas");
        _canvas.setAttribute("width", width);
        _canvas.setAttribute("height", height);
        _canvas.getContext("2d").drawImage(_img, 0, 0, Number(width), Number(height));
        newbase64 = _canvas.toDataURL("image/jpeg");
        callback ? callback(newbase64) : null; //调用回调函数
      }
    }
  }

}
